 import Food from './food.js'
 import Snake from './snake.js'
 export default   class Game{
     constructor(ele,score){
         this.map = document.querySelector(ele)

         //获取计分牌
         this.score = document.querySelector(score)



         //创建一个食物
         this.food = new Food(this.map)

         //创建一个蛇
         this.snake = new Snake(this.map)
         this.change()

        //准备级别
        this.level = 3

        //准备一个变量接收定时器返回值
        this.timer = 0

        //准备变量用作计数
        this.count = 0



     }

     // 1.开始游戏
     start(){
         this.timer = setInterval(()=>{
             //移动
             this.snake.move()

             //判断吃到食物
             if(this.snake.isEat(this.food)){
                 this.updateScore()
                 this.snake.creHead()
                 this.food.newFood()

             }


             //判断死亡
             if(this.snake.isDie()){
                window.alert("GAME OVER")
                clearInterval(this.timer)
             }

         },500- this.level*50)

     } 

     // 2.暂停游戏
     stop(){
         clearInterval(this.timer)
     }

     // 3.重新开始游戏
     restart(){
         window.location.reload()
     }

     // 4.修改方向
     change(){
         document.addEventListener('keydown',e=>{
             e=e||window.event
             const code = e.keyCode || e.which
             switch(code){
                 case 37:this.snake.direction = 'left';break
                 case 38:this.snake.direction = 'top';break
                 case 39:this.snake.direction = 'right';break
                 case 40:this.snake.direction = 'bottom';break
             }
         })
     }

     // 5.计分
     updateScore(){
         this.count++
         this.score.value=this.count*90+this.level*10
         if(this.count %15===0){
             this.level++
             this.stop()
             this.start()
         }
     }

 }